package com.xmy.aboutThread;

// wait() notify() 生产者-消费者模式


public class Demo8 {

    private static Boolean hasProduct = false;

    private static final Object lock = new Object();

    public static void main(String[] args) {

        new Thread(new Consumer()).start();

        new Thread(new Producer()).start();

    }

    // 消费者

    static class Consumer implements Runnable {

        @Override
        public void run() {
            synchronized (lock) {

                while (!hasProduct) {
                    System.out.println("还没生产好呢！我得等了。");

                    try {
                        lock.notify();

                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.println("我终于买到货了");
            }
        }
    }

    // 生产者
    static class Producer implements Runnable {

        @Override
        public void run() {
            synchronized (lock) {

                System.out.println("生产中...");

                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("生产完毕");

                lock.notify();

                hasProduct = true;
            }
        }
    }
}
